package com.example.demo.slice;

import com.bluelinelabs.logansquare.LoganSquare;
import com.bumptech.glide.Glide;
import com.example.demo.ResourceTable;
import com.example.demo.base.Global;
import com.example.demo.base.GlobalIntentHelper;
import com.example.demo.model.JsonsRootBean;
import com.example.demo.msic.S;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;

import java.io.IOException;

public class MainAbilitySlice extends AbilitySlice {
    private Image mImage;
    private Button mBtnVoice;
    private Text mTvData;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
        initData();
    }

    public void initView() {
        mImage = (Image) findComponentById(ResourceTable.Id_iv_logo);
        mBtnVoice = (Button) findComponentById(ResourceTable.Id_btnLoad);
        mTvData = (Text) findComponentById(ResourceTable.Id_tv_data);
        mBtnVoice.setClickedListener(component -> requestData());
        findComponentById(ResourceTable.Id_btn_voice_ability).setClickedListener(mListener);
        findComponentById(ResourceTable.Id_btn_login).setClickedListener(component -> jumpLoginAbility());
        findComponentById(ResourceTable.Id_btn_tab).setClickedListener(component -> jumpTab());
    }

    private void initData() {
        Glide.with(this)
                .load(S.url)
                .into(mImage);
    }

    private void requestData() {
        OkGo.<String>get(S.BASE_URL)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JsonsRootBean data = LoganSquare.parse(response.body(), JsonsRootBean.class);
                            Global.showToast(data.getMessage());
                            mTvData.setText(data.getMessage());
                        } catch (IOException e) {
                            Global.showToast("解析失败!");
                        }
                    }
                });
    }

    private Component.ClickedListener mListener = component -> {
        switch (component.getId()) {
            case ResourceTable.Id_btn_voice_ability:
                jumpVoiceAbility();
                break;
        }
    };

    private void jumpVoiceAbility() {
        GlobalIntentHelper.jumpAbility(this, S.AbilityRes.VOICE);
    }

    private void jumpLoginAbility() {
        GlobalIntentHelper.jumpAbility(this, S.AbilityRes.LOGIN);
    }

    private void jumpTab() {
        GlobalIntentHelper.jumpAbility(this, S.AbilityRes.TAB);
    }
}
